<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <title>文件上传与下载示例</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        h2 { margin-bottom: 10px; }
        ul { list-style-type: none; padding: 0; }
        li { margin: 5px 0; }
        .file-entry { display: flex; align-items: center; justify-content: space-between; width: 400px; }
        .upload-section { margin-top: 30px; }
    </style>
</head>
<body>
<h2>📂已上传文件</h2>
<ul id="fileList"></ul>

<div class="upload-section">
    <h2>📤上传新文件</h2>
    <form id="uploadForm">
        <input type="file" name="file" required />
        <button type="submit">上传</button>
    </form>
    <p id="uploadStatus"></p>
</div>

<script>
    // 加载文件列表
    async function loadFiles() {
      const res = await fetch('/files/list');
      const files = await res.json();
      const fileList = document.getElementById('fileList');
      fileList.innerHTML = '';
      files.forEach(file => {
        const li = document.createElement('li');
        li.className = 'file-entry';
        li.innerHTML = `
          <span>${file}</span>
          <button onclick="downloadFile('${file}')">下载</button>
        `;
        fileList.appendChild(li);
      });
    }

    // 下载功能
    function downloadFile(filename) {
      window.location.href = `/files/download?filename=${encodeURIComponent(filename)}`;
    }

    // 上传功能
    document.getElementById('uploadForm').addEventListener('submit', async function (e) {
      e.preventDefault();
      const formData = new FormData(this);
      const res = await fetch('/files/upload', {
        method: 'POST',
        body: formData
      });
      const text = await res.text();
      document.getElementById('uploadStatus').textContent = text;
      this.reset();
      loadFiles(); // 上传后刷新文件列表
    });

    // 初始化
    loadFiles();
</script>
</body>
</html>
